//获取权限方法
var userInfo = getAuthority();
var powerlist = JSON.parse(userInfo).permissions;
/*自定义函数判断权限*/
template.defaults.imports.hasPower = function(data){
    if(powerlist.includes(data)){
        return true;
    }
    return false;
};

layui.use(['layer', 'form', 'table', 'util', 'dtree'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var util = layui.util;
    var dtree = layui.dtree;
    var admin = layui.admin;

    var selectedRegionClass="";//选中的区划分类
    var selectedRegionCatalog = "";//选中的区划配置ID
    var catalogData = [];//区划配置数据
    var regionClass = [];//区划分类数据
    var selectRinfoData = [];//已经关联的区划
    var regionClassLog = [];//存放区划分类展开项
    var setting={//树设置
        regionClass:{//区划分类
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false,
                drag: {
                    isCopy: true,
                    isMove: false,
                    prev: false,
                    next: false,
                    inner: false
                }
            },
            data: {
                key: {
                    name: "name",
                    children: "resultData"
                },
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onClick: zTreeRegionClassOnClick,
                onExpand: onExpandRegionClass,
                beforeCollapse: onRegionClassBeforeCollapse
            },
            view: {
                showIcon: true,
                showLine: true
            }
        },
        regionSetting:{//区划树设置
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false,
                drag: {
                    isCopy: true,
                    isMove: false,
                    prev: false,
                    next: false,
                    inner: false
                }
            },
            data: {
                key: {
                    name: "name",
                    children: "children"
                },
                simpleData: {
                    enable: true
                }
            },
            check: {
                enable: true,
                chkboxType: { "Y": "s", "N": "s" }
            },
            callback: {
                onExpand: onExpandRegionTree,
            },
            view: {
                showIcon: true,
                showLine: true
            }
        }
    }

    if(userInfo){
        var access_token = localStorage.getExpire("access_token");
        var token_type = localStorage.getExpire("token_type");
        Authorization = token_type+" "+access_token;

        getRegionClassPower();
        getRegionTreePower();
        getCatalogData();

    }
    form.on('select(CatalogVersion)', function(data){
        selectedRegionCatalog = data.value;
        getRegionClassData(data.value)
        $("#regionTree").empty();
    });

    // 添加
    $('#add-btn-class').click(function () {
        showAddClassModel();
    });
    // 修改
    $('#edit-btn-class').click(function () {
        if(selectedRegionClass.hasOwnProperty("id")){
            showEditModle(selectedRegionClass);
        }else{
            layer.msg('请选择需要编辑的区划分类子类');
        }
    });
    //删除
    $('#delete-btn-class').click(function () {
        if(selectedRegionClass.hasOwnProperty("id")){
            doDeleteModel(selectedRegionClass);
        }else{
            layer.msg('请选择需要删除的区划分类子类');
        }

    });

    $('#update-btn-rinfo').click(function () {
        addRinfo();
    });

    function getRegionClassPower() {
        var str = template("regionClass-tmpl",{});
        document.getElementById("regionClass-tmpl-box").innerHTML = str;
        form.render('select')
    }

    function getRegionTreePower() {
        var str = template("regionTree-tmpl",{});
        document.getElementById("regionTree-tmpl-box").innerHTML = str;
    }

    /*获取区划配置列表*/
    function getCatalogData(){
        var req={
            current: 1,
            size: 100,
            flag:0
        };
        axios.get(regionUrl.catalog.catalogList,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    catalogData = response.data.data;
                    var str = template("Catalog-tmpl",catalogData);
                    document.getElementById("regionClassTypeBox").innerHTML = str;
                    form.render('select')
                    selectedRegionCatalog = catalogData.records[0].id;
                    getRegionClassData();
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }

    /*获取区划分类树数据*/
    function getRegionClassData(rcid) {
        var req = {
            rcid:rcid||selectedRegionCatalog||''
        }
        axios.get(regionUrl.class.queryClass,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var datas = response.data.data;
                    regionClass = response.data;
                    if (datas.length > 0) {
                        for (const row of datas) {
                            row.isParent = true;
                            row.name = row.message;
                            if(regionClassLog.includes(row.code)){
                                row.open = true;
                            }
                        }
                    }
                    $.fn.zTree.init($("#regionClassTree"), setting.regionClass, datas);
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });

    }

    //区划分类选中事件
    function zTreeRegionClassOnClick(event, treeId, treeNode){
        selectedRegionClass = treeNode;
        if(selectedRegionClass.hasOwnProperty("id")){//选中子类才查询区划树
            selectedRegionCatalog = treeNode.rcid;
            selectRinfo();
        }else{
            $.fn.zTree.init($("#regionTree"), setting.regionSetting, []);
        }
    }

    //添加弹窗
    function showAddClassModel(obj) {
        admin.open({
            type: 1,
            title: '新增区划分类',
            area: ['350px', '480px'],
            offset:'auto',
            content: $('#addClassifyForm').html(),
            success: function (layero, dIndex) {
                var str = template("Catalog-tmpl",catalogData);
                document.getElementById("addClassRegionCatalog").innerHTML = str;
                var classstr = template("region-class-tmpl",regionClass);
                document.getElementById("addClassRegionClass").innerHTML = classstr;

                form.render('select'); //刷新select选择框渲染
                form.on('submit(modelSubmitUser)', function (data) {
                    let req = {
                        name:data.field.name,
                        rcid:data.field.rcid,
                        regionClass:data.field.regionClass,
                        memo:data.field.memo
                    }
                    axios({
                        method: 'POST',
                        url:regionUrl.class.addClass,
                        data:$.param(req),
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (response) {
                            if(response.status == 200 &&response.data.message == "success"){
                                layer.close(dIndex);
                                layer.closeAll('loading');
                                layer.msg("新增成功", {icon: 1});
                                getRegionClassData();
                            }else{
                                layer.closeAll('loading');
                                layer.msg("新增失败，详情："+response.data.message, {icon: 2});
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                            if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                                // 进行重新登陆
                                localStorage.clear();
                                top.location.href=loginPageUrl;
                            }
                        });
                    return false;
                });

            }
        });
    }

    //编辑弹窗
    function showEditModle(obj){
        admin.open({
            type: 1,
            title: '编辑区划分类',
            area: ['350px', '480px'],
            offset:'auto',
            content: $('#editClassModel').html(),
            success: function (layero, dIndex) {
                form.val("editClassForm",obj)
                form.on('submit(editClassSubmit)', function (data) {
                    let req = {
                        name:data.field.name,
                        memo:data.field.memo,
                        rcid:obj.rcid,
                        regionClass:obj.regionClass,
                        id:obj.id,
                        version:obj.version
                    }
                    axios({
                        method: 'PUT',
                        url:regionUrl.class.editClass,
                        data:$.param(req),
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (response) {
                            if(response.status == 200 &&response.data.message == "success"){
                                layer.close(dIndex);
                                layer.closeAll('loading');
                                layer.msg("编辑成功", {icon: 1});
                                getRegionClassData();
                            }else{
                                layer.closeAll('loading');
                                layer.msg("编辑失败，详情："+response.data.message, {icon: 2});
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                            if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                                // 进行重新登陆
                                localStorage.clear();
                                top.location.href=loginPageUrl;
                            }
                        });
                    return false;
                })


            }
        });
    }

    // 删除
    function doDeleteModel(obj) {
        layer.confirm('确定要删除“' + obj.name + '”分类吗？', {
            skin: 'layui-layer-admin',
            shade: .1,
        }, function (i) {
            layer.close(i);
            layer.load(2);
            axios({
                method: 'delete',
                url:regionUrl.class.deleteClass+obj.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg("成功删除", {icon: 1});
                        getRegionClassData();
                    } else {
                        layer.closeAll('loading');
                        layer.msg("删除失败，详情："+res.data.message, {icon: 2});
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                })
        });
    }

    //关联查询
    function selectRinfo() {
        var req = {
            recid:selectedRegionClass.id
        }
        axios.get(regionUrl.class.getSelectRinfo,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var datas = response.data.data;
                    selectRinfoData = datas;
                    lazyLoadRegionTree();
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }

    //懒加载区划树
    function lazyLoadRegionTree() {
        var req={
            rcId : selectedRegionCatalog,
            regionCode: "",
            regionCodeType:""
        };
        axios.get(regionUrl.info.queryRegion,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var datas = response.data.data;
                    if (datas.length > 0) {
                        for (const row of datas) {
                            row.isParent = true;
                            row.children = []; //存放子节点
                            for(var item in selectRinfoData){
                                if(selectRinfoData[item].id == row.id){//已经关联的区划选中
                                    row.checked = true;
                                }
                            }
                            // if(selectRinfoData.includes(row.id)){//已经关联的区划选中
                            //     row.checked = true;
                            // }else{
                            //     row.checked = false;
                            // }
                        }
                    }
                    $.fn.zTree.init($("#regionTree"), setting.regionSetting, datas);
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }

    //展开下级区划
    function onExpandRegionTree(event, treeId, treeNode){
        if(treeNode.children.length==0){
            var req={
                rcId : selectedRegionCatalog,
                regionCode: treeNode.code,
                regionCodeType:""
            };
            axios.get(regionUrl.info.queryRegion,{
                params: req,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        var datas = response.data.data;
                        if (datas.length > 0) {
                            for (const row of datas) {
                                row.isParent = true;
                                row.children = []; //存放子节点
                                for(var item in selectRinfoData){
                                    if(selectRinfoData[item].id == row.id){//已经关联的区划选中
                                        row.checked = true;
                                    }
                                }
                                // if(selectRinfoData.includes(row.id)){//已经关联的区划选中
                                //     row.checked = true;
                                // }else{
                                //     row.checked = false;
                                // }
                            }
                        }
                        const treeObj = $.fn.zTree.getZTreeObj("regionTree");
                        treeObj.addNodes(treeNode, datas);
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        }
    }

    //展开区划分类
    function onExpandRegionClass(event, treeId, treeNode){
        regionClassLog.push(treeNode.code)
    }

    //折叠区划分类
    function onRegionClassBeforeCollapse(event, treeId, treeNode) {
        var index = regionClassLog.indexOf(treeId.code);
        if( index!=-1 ){
            regionClassLog.splice(index,1);
        }
    }

    //区划分类关联更新
    function addRinfo(){
        if(selectedRegionClass.id){
            var treeObj = $.fn.zTree.getZTreeObj("regionTree");
            var nodes = treeObj.getCheckedNodes(true);

            var regionIds = [];
            for(let i in nodes){
                regionIds.push(nodes[i].id);
            }
            var formData = new FormData();
            formData.append("recid",selectedRegionClass.id);
            formData.append("regionIds",regionIds)
            axios({
                method: 'POST',
                url:regionUrl.class.addRinfo,
                data:formData,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        layer.closeAll('loading');
                        layer.msg("更新成功", {icon: 1});
                    }else{
                        layer.closeAll('loading');
                        layer.msg("更新失败，详情："+response.data.message, {icon: 2});
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        }else{
            layer.msg("请先选择一个区划分类", {icon: 1});
        }

    }

});